Skip to content

Latest commit

 

History

History
96 lines (80 loc) · 1.76 KB

File metadata and controls

96 lines (80 loc) · 1.76 KB

114. Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

 1 / \ 2 5 / \ \ 3 4 6 

The flattened tree should look like:

1 \ 2 \ 3 \ 4 \ 5 \ 6 

Solutions (Python)

1. DFS

# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution: defflatten(self, root: TreeNode) ->None: """ Do not return anything, modify root in-place instead. """ifnotroot: returnNonestack= [root] prev=TreeNode(left=root) whilestack: curr=stack.pop() prev.left=Noneprev.right=currifcurr.right: stack.append(curr.right) ifcurr.left: stack.append(curr.left) prev=curr

Solutions (Ruby)

1. DFS

# Definition for a binary tree node.# class TreeNode# attr_accessor :val, :left, :right# def initialize(val = 0, left = nil, right = nil)# @val = val# @left = left# @right = right# end# end# @param {TreeNode} root# @return {Void} Do not return anything, modify root in-place instead.defflatten(root)returnnilifroot.nil?stack=[root]prev=TreeNode.new(left=root)while not stack.empty?curr=stack.popprev.left=nilprev.right=currstack.push(curr.right)if not curr.right.nil?stack.push(curr.left)if not curr.left.nil?prev=currendend
close